//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin,reqUserInfo } from '@/api/user'
//引入操作本地存储的工具方法
import { SET_TOKEN, SET_USERID,SET_AVATAR,SET_USERNAME,SET_FRIENDS,GET_TOKEN,GET_AVATAR,GET_USERID,GET_USERNAME,GET_FRIENDS,REMOVE_AVATAR,REMOVE_USERID,REMOVE_USERNAME, REMOVE_TOKEN ,REMOVE_FRIENDS} from '@/utils/token'
import type{reqLoginData,ReqfriendsData,friendsData} from '@/types/type'


//创建用户小仓库
const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: () => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      username:GET_USERNAME(),
      avatar:GET_AVATAR(),
      userId:GET_USERID(),
      friendsList :GET_FRIENDS(), // 全部好友
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: any) {
      //登录请求
      const result: reqLoginData = await reqLogin(data)
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data.token as string
        this.username=result.data.username as string
        this.userId=result.data._id as string
        this.avatar=result.data.avatar as string
        //本地存储持久化存储一份
        SET_TOKEN(result.data.token as string)
        SET_USERID(result.data._id as string)
        SET_AVATAR(result.data.avatar as string)
        SET_USERNAME(result.data.username as string)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    // 获取用户全部好友
    async getfriend(userId:any){
      const result: ReqfriendsData = await reqUserInfo({ userId });
      if (result.code == 200) {
        // 不直接赋值，而是通过数组操作保持响应式
        this.friendsList.splice(0, this.friendsList.length, ...result.data);
        SET_FRIENDS(result.data)
    }
      },
    //退出登录
    async userLogout() {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        REMOVE_AVATAR()
        REMOVE_USERID()
        REMOVE_USERNAME()
        REMOVE_FRIENDS()
        return 'ok'
  },
  getters: {},
}})
//对外暴露获取小仓库方法
export default useUserStore
